<template>
  <div>
    <!-- 背景 -->
    <div
      class="fixed w-dvw h-dvh inset-0 bg-gray-500/75 z-50"
      :style="{ display: open ? 'block' : 'none' }"
    ></div>
    <!-- dialog -->
    <div
      role="dialog"
      :id="dialogID"
      class="max-w-sm min-w-64 border shadow rounded"
      popover="manual"
      @toggle="toggleDialogEvent"
      ref="dialog"
    >
      <div>
        <!-- header -->
        <div
          class="flex justify-between items-center h-12 box-border px-3 py-2"
        >
          <!-- title -->
          <div>{{ title }}</div>
          <!-- action -->
          <div v-if="closeButton">
            <button
              class="border rounded px-2 bg-base-200 hover:bg-base-300 active:scale-90"
              :popovertarget="dialogID"
              popovertargetaction="hide"
            >
              X
            </button>
          </div>
        </div>
        <!-- 分割线 -->
        <div class="border"></div>
        <!-- body -->
        <div class="box-border px-3 py-2">
          <slot></slot>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      open: false,
      dialogID: "dialog-popover-" + new Date().getTime(),
    };
  },

  props: {
    title: {
      type: String,
      default: "标题",
    },
    closeButton: {
      type: Boolean,
      default: true,
    },
  },

  methods: {
    toggleDialogEvent(e) {
      if (e.newState === "open") {
        this.open = true;
      } else if (e.newState === "closed") {
        this.open = false;
      }
      this.$emit("toggle", this.open);
    },
    show() {
      if (this.$refs.dialog.open) {
        return;
      }
      this.$refs.dialog.showPopover();
      this.open = true;
      this.$emit("show");
    },
    hide() {
      if (!this.$refs.dialog.open) {
        return;
      }
      this.$refs.dialog.hidePopover();
      this.open = false;
      this.$emit("hide");
    },
    toggle() {
      this.$refs.dialog.togglePopover();
      this.open = !this.open;
    },
  },
};
</script>
